/**
 * 路由初始化
 * @module router/index
 */
import Vue from 'vue'
import Router from 'vue-router'
import routes from './routes'
import store from '../store/index'
import {LOGIN_PATH} from '../config'
import {getCurrentUser} from '../helper/before'

const router = new Router(routes)

Vue.use(Router)

router.beforeEach((to, from, next) => {
  let loginFun = () => {
    if (to.fullPath !== LOGIN_PATH) { // 判断是否为登录页请求
      let loginUser = store.state.userInfo.userInfo
      if (!loginUser) {
        getCurrentUser()
          .then(() => {
            next()
          })
          .catch(e => {
            router.push(LOGIN_PATH)
          })
      } else {
        next()
      }
    } else {
      next()
    }
  }
  loginFun()
})

export default router
